"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : DMS分布式锁
Case Name   : 存储过程获取锁、解锁、锁冲突操作
Create At   : 2023/4/21
Owner       : opentestcase033
Description :
    1.创建存储过程
    2.开启事务a，重命名存储过程名称，不提交，事务b执行后提交
    3.开启事务b，修改存储过程所属表空间为pg_default
    4.清理环境
Expect:
    1.设置成功
    2.执行成功，获取锁
    3.等锁释放，事务a提交(解锁)，事务b执行失败
    4.成功
History     :
"""

import os
import time
import unittest

from testcase.utils.Logger import Logger
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.ComThread import ComThread


class DmsOck(unittest.TestCase):

    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.constant = Constant()
        self.procedure = 'pro_dms_ock_0018'
        self.schema = 'sch_dms_ock_0018'

    def test_dms_ock(self):
        text1 = '-----step1:创建存储过程;expect:成功-----'
        self.log.info(text1)
        create_pro = f"""drop procedure if exists {self.procedure};
        create or replace procedure {self.procedure}() is
        var1 int:= 1;
        var2 int:= 2;
        begin
        drop table if exists t_dms_ock_0018;
        create table t_dms_ock_0018(c_int int)with (segment=on);
        insert into t_dms_ock_0018 values(var1),(var2);
        end; """
        create_pro_res = self.pri_sh.execut_db_sql(create_pro)
        self.log.info(create_pro_res)
        self.assertIn(self.constant.CREATE_PROCEDURE_SUCCESS_MSG,
                      create_pro_res, f"执行失败:{text1}")

        text2 = '-----step2:创建schema;expect:成功-----'
        self.log.info(text2)
        create_sch = f"drop schema if exists {self.schema};" \
                     f"create schema {self.schema};"
        create_sch_res = self.pri_sh.execut_db_sql(create_sch)
        self.log.info(create_sch_res)
        self.assertIn(self.constant.CREATE_SCHEMA_SUCCESS_MSG,
                      create_sch_res, f"执行失败:{text2}")

        text3 = '-----step3:开启事务a，重命名存储过程，不提交，' \
                '事务b执行后回滚;expect:执行成功-----'
        self.log.info(text3)
        sql1 = f"start transaction;" \
               f"alter procedure {self.procedure}() " \
               f"rename to copy_{self.procedure};" \
               f"select pg_sleep(3);" \
               f"rollback;"
        session1 = ComThread(self.pri_sh.execut_db_sql, args=(sql1,))
        session1.setDaemon(True)
        session1.start()
        time.sleep(1)

        text4 = '-----step4:开启事务b，修改存储过程所属模式;' \
                'expect:等锁释放，事务a回滚(解锁)，事务b执行成功-----'
        self.log.info(text4)
        sql2 = f"begin;" \
               f"alter procedure {self.procedure}() set schema {self.schema}"
        session2 = ComThread(self.pri_sh.execut_db_sql, args=(sql2,))
        session2.setDaemon(True)
        session2.start()
        session1.join(10)
        session2.join(10)
        result1 = session1.get_result()
        self.log.info(f'session1_results: {result1}')
        result2 = session2.get_result()
        self.log.info(f'session2_results: {result2}')
        self.assertIn(self.constant.START_TRANSACTION_SUCCESS_MSG,
                      result1, f"执行失败:{text3}")
        self.assertIn(self.constant.ALTER_FUNCTION_SUCCESS_MSG, result1,
                      f"执行失败:{text3}")
        self.assertIn(self.constant.ROLLBACK_MSG, result1, f"执行失败: {text3}")
        self.assertIn(self.constant.ALTER_FUNCTION_SUCCESS_MSG,
                      result2, f"执行失败{text4}")

    def tearDown(self):
        text5 = '-----step5:清理环境 expect:成功-----'
        self.log.info(text5)
        drop_db_res = self.pri_sh.execut_db_sql(
            f"drop procedure if exists {self.procedure};"
            f"drop database if exists copy_{self.procedure};")
        self.log.info(drop_db_res)
        self.assertIn(self.constant.DROP_PROCEDURE_SUCCESS_MSG,
                      drop_db_res, f"删表失败:{text5}")
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
